﻿using MediatR;
using SmartTracking.API.Read.Application.Commands.PoultryHouse_command;
using SmartTracking.API.Read.DTO;
using SmartTracking.Domain.Sheep;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Read.Application.CommandHandlers.PoultryHouse_handler
{
    public class GetPoultryHouseCommandHandler:IRequestHandler<GetPoultryHouseCommand,ApiResult<ApiPaging<PoultryHouse>>>
    {
        private readonly IBaseRepository<PoultryHouse> houseRep;

        public GetPoultryHouseCommandHandler(
            IBaseRepository<PoultryHouse> houseRep)
        {
            this.houseRep = houseRep;
        }

        public Task<ApiResult<ApiPaging<PoultryHouse>>> Handle(GetPoultryHouseCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<PoultryHouse>> result = new ApiResult<ApiPaging<PoultryHouse>>();
            result.Code = ApiEnum.查询成功;
            result.Message = ApiEnum.查询成功.ToString();

            var list = houseRep.GetAll().Where(x => x.IsDeleted == false);
            if(!string.IsNullOrEmpty(request.HouseName))
            {
                list = list.Where(x => x.HouseName.Equals(request.HouseName));
            }
            if(!string.IsNullOrEmpty(request.PersonInCharge))
            {
                list = list.Where(x => x.PersonInCharge.Equals(request.PersonInCharge));
            }
            if(request.HouseTypeId != 0)
            {
                list = list.Where(x => x.HouseTypeId == request.HouseTypeId);
            }

            int ListCount = list.Count();
            int PageCount = (int)Math.Ceiling(ListCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(x => x.HouseId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            ApiPaging<PoultryHouse> paging = new ApiPaging<PoultryHouse>();
            paging.totalCount = ListCount;
            paging.totalPage = PageCount;
            paging.data = list.ToList();

            result.data = paging;
            return Task.FromResult(result);
        }
    }
}
